/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.source.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JaxbMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.utils.*;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.publish.entity.EleSourceGroupPublish;
import com.thinkgem.jeesite.modules.publish.entity.EleTempletPublish;
import com.thinkgem.jeesite.modules.publish.service.EleSourceGroupPublishService;
import com.thinkgem.jeesite.modules.source.dao.image.EleSourceImageDao;
import com.thinkgem.jeesite.modules.source.entity.EleSource;
import com.thinkgem.jeesite.modules.source.entity.EleSourceGroup;
import com.thinkgem.jeesite.modules.source.entity.EleSourceMultimedia;
import com.thinkgem.jeesite.modules.source.entity.alarm.EleSourceAlarm;
import com.thinkgem.jeesite.modules.source.entity.alarm.EleSourceAlarmGroup;
import com.thinkgem.jeesite.modules.source.entity.app.EleSourceApp;
import com.thinkgem.jeesite.modules.source.entity.background.EleSourceBackground;
import com.thinkgem.jeesite.modules.source.entity.direction.EleSourceDirection;
import com.thinkgem.jeesite.modules.source.entity.direction.EleSourceDirectionGroup;
import com.thinkgem.jeesite.modules.source.entity.floor.EleSourceFloor;
import com.thinkgem.jeesite.modules.source.entity.floor.EleSourceFloored;
import com.thinkgem.jeesite.modules.source.entity.floor.Floor;
import com.thinkgem.jeesite.modules.source.entity.floor.FloorNode;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImage;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImageGroup;
import com.thinkgem.jeesite.modules.source.entity.logo.EleSourceLogo;
import com.thinkgem.jeesite.modules.source.entity.subtitle.EleSourceSubtitle;
import com.thinkgem.jeesite.modules.source.entity.subtitle.EleSourceSubtitleGroup;
import com.thinkgem.jeesite.modules.source.entity.time.EleSourceDate;
import com.thinkgem.jeesite.modules.source.entity.time.EleSourceTime;
import com.thinkgem.jeesite.modules.source.entity.title.EleSourceTitle;
import com.thinkgem.jeesite.modules.source.entity.video.EleSourceVideo;
import com.thinkgem.jeesite.modules.source.entity.video.EleSourceVideoGroup;
import com.thinkgem.jeesite.modules.source.entity.weather.EleSourceWeather;
import com.thinkgem.jeesite.modules.source.entity.week.EleSourceWeek;
import com.thinkgem.jeesite.modules.source.service.EleSourceGroupService;
import com.thinkgem.jeesite.modules.source.service.EleSourceMultimediaService;
import com.thinkgem.jeesite.modules.source.service.alarm.EleSourceAlarmGroupService;
import com.thinkgem.jeesite.modules.source.service.app.EleSourceAppService;
import com.thinkgem.jeesite.modules.source.service.background.EleSourceBackgroundService;
import com.thinkgem.jeesite.modules.source.service.direction.EleSourceDirectionGroupService;
import com.thinkgem.jeesite.modules.source.service.floor.EleSourceFloorService;
import com.thinkgem.jeesite.modules.source.service.floor.EleSourceFlooredService;
import com.thinkgem.jeesite.modules.source.service.floor.FloorNodeService;
import com.thinkgem.jeesite.modules.source.service.image.EleSourceImageGroupService;
import com.thinkgem.jeesite.modules.source.service.logo.EleSourceLogoService;
import com.thinkgem.jeesite.modules.source.service.subtitle.EleSourceSubtitleGroupService;
import com.thinkgem.jeesite.modules.source.service.time.EleSourceDateService;
import com.thinkgem.jeesite.modules.source.service.time.EleSourceTimeService;
import com.thinkgem.jeesite.modules.source.service.title.EleSourceTitleService;
import com.thinkgem.jeesite.modules.source.service.video.EleSourceVideoGroupService;
import com.thinkgem.jeesite.modules.source.service.video.EleSourceVideoService;
import com.thinkgem.jeesite.modules.source.service.weather.EleSourceWeatherService;
import com.thinkgem.jeesite.modules.source.service.week.EleSourceWeekService;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.templet.entity.EleTemplet;
import com.thinkgem.jeesite.modules.templet.service.EleTempletService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 节目包管理Controller
 *
 * @author ZC
 * @version 2017-05-25
 */
@Controller
@RequestMapping(value = "${adminPath}/source/eleSourceGroup")
public class EleSourceGroupController extends BaseController{

    @Autowired
    private EleSourceGroupService eleSourceGroupService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private EleEquipmentService eleEquipmentService;
    @Autowired
    private EleSourceGroupPublishService eleSourceGroupPublishService;
    @Autowired
    private EleTempletService eleTempletService;
    @Autowired
    private FloorNodeService floorNodeService;

    @Autowired
    private SystemService systemService;
    @Autowired
    private EleSourceVideoService videoService;
    @Autowired
    private EleSourceImageDao imageService;
    @Autowired
    private EleSourceMultimediaService eleSourceMultimediaService;
    @Autowired
    private EleSourceImageGroupService eleSourceImageGroupService;
    @Autowired
    private EleSourceVideoGroupService eleSourceVideoGroupService;
    @Autowired
    private EleSourceSubtitleGroupService eleSourceSubtitleGroupService;
    @Autowired
    private EleSourceTitleService eleSourceTitleService;

    @Autowired
    private EleSourceDirectionGroupService eleSourceDirectionGroupService;
    @Autowired
    private EleSourceBackgroundService eleSourceBackgroundService;
    @Autowired
    private EleSourceAlarmGroupService eleSourceAlarmGroupService;
    @Autowired
    private EleSourceDateService eleSourceDateService;
    @Autowired
    private EleSourceTimeService eleSourceTimeService;

    @Autowired
    private EleSourceWeatherService eleSourceWeatherService;
    @Autowired
    private EleSourceWeekService eleSourceWeekService;
    @Autowired
    private EleSourceFloorService eleSourceFloorService;
    @Autowired
    private EleSourceFlooredService eleSourceFlooredService;
    @Autowired
    private EleSourceLogoService eleSourceLogoService;

    @Autowired
    private EleSourceAppService eleSourceAppService;
    @Autowired
    private EleSourceFloorService floorService;


    @ModelAttribute
    public EleSourceGroup get(@RequestParam(required = false) String id){
        EleSourceGroup entity = null;
        if(StringUtils.isNotBlank(id)){
            entity = eleSourceGroupService.get(id);
        }
        if(entity == null){
            entity = new EleSourceGroup();
        }
        return entity;
    }

    @RequiresPermissions("source:eleSourceGroup:view")
    @RequestMapping(value = {"list", ""})
    public String list(EleSourceGroup eleSourceGroup, HttpServletRequest request, HttpServletResponse response,
                       Model model){
    	User user = UserUtils.getUser();
		List<User> list = null;
		if(user.isAdmin()) {
			list = systemService.findAllUsers(user);
		}else {
			list = systemService.findAllUsersInCompany(user);
			list.add(UserUtils.getAdminUser());		
		}		
		eleSourceGroup.setUsers(list);
        Page<EleSourceGroup> page = eleSourceGroupService.findPage(new Page<EleSourceGroup>(request, response),
                eleSourceGroup);
    	Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
        model.addAttribute("page", page);
        return "modules/source/eleSourceGroupList";
    }

    @RequiresPermissions("source:eleSourceGroup:view")
    @RequestMapping(value = "form")
    public String form(EleSourceGroup eleSourceGroup, Model model){
        model.addAttribute("eleSourceGroup", eleSourceGroup);
        List<EleSource> esList = eleSourceGroup.getEleSourceList();
        return "modules/source/eleSourceGroupForm";
    }

    @RequiresPermissions("source:eleSourceGroup:view")
    @RequestMapping(value = "equipmentlist")
    public String equipmentList(EleEquipment eleEquipment, Model model){
        List<Office> listTree = new ArrayList<>();

        User current = UserUtils.getUser();

        List<User> resultList = getBranchForUser(current);
        Set<String> ids = new HashSet<String>();
        for(User temuser : resultList){
            String officeId = temuser.getOffice().getId();
            String companyId = temuser.getCompany().getId();
            ids.add(officeId);
            ids.add(companyId);
        }
        List<Office> listOffice = officeService.findList(true);


        Set<String> officeIds = new HashSet<>();
        Set<String> eqIds = new HashSet<>();
        for(User tmp : resultList){
            EleEquipment eleEquipmentTmp = new EleEquipment();
            eleEquipmentTmp.setCompany(tmp.getCompany());
            eleEquipmentTmp.setOffice(tmp.getOffice());

            List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipment);
            for(EleEquipment equipment : listEquipment){
                officeIds.add(equipment.getCompany().getId());
                officeIds.add(equipment.getOffice().getId());
                if(eqIds.contains(equipment.getId())){
                    continue;
                }
                eqIds.add(equipment.getId());
                Office Office = new Office();
                Office.setId(equipment.getId());
                Office.setParent(new Office(equipment.getOffice().getId()));
                Office.setAddress(equipment.getCode());
                Office.setEmail(equipment.getType().getName());
                Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
                Office.setRemarks(equipment.getRemarks());
                if("1".equals(equipment.getState())){
                    Office.setGrade("在线");
                }
                else{
                    Office.setGrade("离线");
                }
                Office.setPhone("");
				Office.setZipCode(equipment.getName());

                listTree.add(Office);
            }
        }
        Set<String> resultSet = new HashSet<String>();
        for(String oid : officeIds){
            resultSet.add(oid);
            Office tmp = officeService.get(oid);
            for(int i = 0; i < listOffice.size(); i++){
                Office item = listOffice.get(i);
                if(item.getId().equals(tmp.getParentId())){
                    System.out.println(item);
                    tmp = item;
                    i = -1;
                    resultSet.add(item.getId());
                }
            }
        }
        for(String oid : resultSet){
            Office item = officeService.get(oid);
            item.setAddress(null);
            item.setEmail(null);
            item.setFax(null);
            item.setRemarks(null);
            item.setGrade(null);
            item.setPhone("display:none;");
			item.setZipCode("");

            listTree.add(item);
        }
        model.addAttribute("list", listTree);
        model.addAttribute("user", current);
        model.addAttribute("eleEquipment", eleEquipment);
        return "modules/source/eleSourceGroupEquipmentList";
    }

    private List<User> getBranchForUser(User current){
        User user = new User();
        List<User> list = systemService.findList(user);
        Role role = current.getRole();
        List<User> resultList = new ArrayList<User>();
        if(current.getUserType().equals("1")){
            resultList = list;
        }
        else if(current.getUserType().equals("4")){
            resultList.add(current);
        }
        else if(current.getUserType().equals("3")){
            for(User usr : list){
                if(usr.getUserType().equals("4")
                        && usr.getCompany().getId().equals(current.getOffice().getId())){
                    resultList.add(usr);
                }
            }
            resultList.add(current);
        }
        else{
            Set<String> offices = new HashSet<String>();
            for(User usr : list){
                if(usr.getUserType().equals("3")
                        && usr.getCompany().getId().equals(current.getOffice().getId())){
                    resultList.add(usr);
                    offices.add(usr.getOffice().getId());
                }
            }
            offices.add(current.getOffice().getId());
            for(User usr : list){
                if(usr.getUserType().equals("4") && offices.contains(usr.getCompany().getId())){
                    resultList.add(usr);
                }
            }
            resultList.add(current);
        }
        return resultList;
    }

    @RequiresPermissions("source:eleSourceGroup:edit")
    @RequestMapping(value = "eleSourceList")
    public String sourceList(HttpServletRequest request, Model model, RedirectAttributes redirectAttributes){
        String egId = request.getParameter("egId");
        String name = request.getParameter("name");
        List<Office> listTree = new ArrayList<>();
        User thisuser = UserUtils.getUser();
        Office office = new Office();

        if(name == null || name == ""){
            EleEquipment equipment = eleEquipmentService.get(egId);
            Office cond = officeService.get(equipment.getOffice().getId());
            office.setParentIds(cond.getParentIds());
            List<Office> list = officeService.findListByParentIds(office);
            for(Office item : list){
                listTree.add(item);
            }
            listTree.add(cond);
            Office Office = new Office();
            Office.setId(equipment.getId());
            Office.setParent(new Office(equipment.getOffice().getId()));
            Office.setAddress(equipment.getCode());
            Office.setEmail(equipment.getType().getModel());
            Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
            Office.setRemarks(equipment.getRemarks());
            Office.setPhone("");
            listTree.add(Office);

            List<EleSource> esList = eleSourceGroupService.findSourcesOnEquipment(equipment.getId(), EleEquipment.DEL_FLAG_NORMAL);
            for(EleSource es : esList){
                Office esOffice = new Office();
                esOffice.setId(es.getId());
                esOffice.setParent(new Office(Office.getId()));
                esOffice.setRemarks(es.getRemarks());
                esOffice.setPhone(es.getName());
                listTree.add(esOffice);
            }
        }
        else{
            Office cond = officeService.get(egId);
            office.setParentIds(cond.getParentIds());
            List<Office> list = officeService.findListByParentIds(office);
            for(Office item : list){
                listTree.add(item);
            }
            listTree.add(cond);
            EleEquipment eleEquipment = new EleEquipment();
            eleEquipment.setOffice(cond);
            List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipment);
            for(EleEquipment equipment : listEquipment){
                Office Office = new Office();
                Office.setId(equipment.getId());
                Office.setParent(new Office(equipment.getOffice().getId()));
                Office.setAddress(equipment.getCode());
                Office.setEmail(equipment.getType().getModel());
                Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
                Office.setRemarks(equipment.getRemarks());
                Office.setPhone("");
                listTree.add(Office);

                List<EleSource> esList = eleSourceGroupService.findSourcesOnEquipment(equipment.getId(), EleEquipment.DEL_FLAG_NORMAL);
                for(EleSource es : esList){
                    Office esOffice = new Office();
                    esOffice.setId(es.getId());
                    esOffice.setParent(new Office(Office.getId()));
                    esOffice.setRemarks(es.getRemarks());
                    esOffice.setPhone(es.getName());
                    listTree.add(esOffice);
                }

            }
        }
        model.addAttribute("list", listTree);
        model.addAttribute("user", thisuser);
        return "modules/source/eleSourceList";
    }

    @RequiresPermissions("source:eleSourceGroup:edit")
    @RequestMapping(value = "next")
    public String next(EleSourceGroup eleSourceGroup, Model model, RedirectAttributes redirectAttributes){
        if(!beanValidator(model, eleSourceGroup)){
            return form(eleSourceGroup, model);
        }
        System.out.println(eleSourceGroup);
        eleSourceGroup.setVisible("1");

        if(eleSourceGroup.getId() == null || eleSourceGroup.getId().isEmpty()){
            eleSourceGroupService.save(eleSourceGroup);
            addMessage(redirectAttributes, "保存节目包成功");
        }
        else{
            eleSourceGroupService.updateGroup(eleSourceGroup);
            addMessage(redirectAttributes, "更新节目包");
        }

        List<EleSource> esList = eleSourceGroup.getEleSourceList();
        if(esList.isEmpty()){
            System.out.println("222222222222222222222222222222222222222");

            addMessage(redirectAttributes, "节目包" + eleSourceGroup.getName() + "缺少节目，请重新配置");
            return "modules/source/eleSourceForm";
        }

//        EleTemplet eleTemplet = eleTempletService.get(eleSourceGroup.getTemplet().getId());
//		if(null != eleTemplet){
//            model.addAttribute("templetSourceList", eleTemplet.getEleTempletSourceList());
//        }

        return "modules/source/eleSourceForm";
    }

    @RequiresPermissions("source:eleSourceGroup:edit")
    @RequestMapping(value = "save")
    public String save(EleSourceGroup eleSourceGroup, Model model, RedirectAttributes redirectAttributes,
                       HttpServletRequest request){
        System.out.println("11111111111111111111111111111");
        if(!beanValidator(model, eleSourceGroup)){
            return form(eleSourceGroup, model);
        }
        System.out.println("22222222222222222222222222222");

        List<EleSource> esList = eleSourceGroup.getEleSourceList();
        if(esList.isEmpty()){
            addMessage(redirectAttributes, "节目包" + eleSourceGroup.getName() + "缺少节目，请重新配置");
            return "modules/source/eleSourceForm";
        }
        System.out.println("3333333333333333333333333333");

        eleSourceGroup.setVisible("1");
        for(EleSource es : esList){
            String name = es.getName();
            System.out.println(name);
            if(name == null){
                continue;
            }
            String[] strs = name.split(",");
            if(strs.length < 2){
                addMessage(redirectAttributes, "节目" + es.getName() + "存在问题，请重新配置");
                return "modules/source/eleSourceForm";
            }
            es.setName(strs[1].trim());
            es.setContent(strs[0].trim());
        }
        //eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_AUDIT);
        eleSourceGroupService.save(eleSourceGroup);

        String basePath = Global.getUserfilesBaseDir();
        System.out.println(basePath);
        try{
            createPackageForSourceGroup(eleSourceGroup, basePath);
        }
        catch(IOException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "modules/source/eleSourceGroupSuccess";
    }

    public boolean createPackageForSourceGroup(EleSourceGroup eleSourceGroup, String basePath) throws IOException{
        List<EleSource> esList = eleSourceGroup.getEleSourceList();
        String egId = eleSourceGroup.getId();
        String encoding = "UTF-8";

//        String filePath = basePath.replace("\\elevator\\","");
        String filePath = basePath.substring(0,basePath.lastIndexOf("\\elevator\\"))+"/";
        Map<String, List<File>> fileMap = new HashMap<>();
        for(EleSource es : esList){
            String type = es.getType();
            if(type == null){
                continue;
            }
            List<File> files = new ArrayList<File>();
            String configName = type + ".xml";
            File config = null;
            String configContent = "";
            switch(type){
//			case "image":
//				EleSourceImageGroup esig = eleSourceImageGroupService.get(es.getContent());
//				List<EleSourceImage> esiList = esig.getEleSourceImageList();
//				for(EleSourceImage esi:esiList){
//					files.add(new File(filePath+esi.getPath()));
//					String path = esi.getPath();
//					path = path.substring(path.lastIndexOf("/")+1, path.length());
//					esi.setPath(path);
//				}
//				configContent = JaxbMapper.toXml(esig, encoding);
//				config = new File(configName);
//				FileUtils.writeStringToFile(config, configContent,encoding, false);
//				files.add(config);
//				break;
//			case "video":
//				EleSourceVideoGroup esvg = eleSourceVideoGroupService.get(es.getContent());
//				List<EleSourceVideo> esvList = esvg.getEleSourceVideoList();
//				for(EleSourceVideo esv:esvList){
//					System.out.println(esv.getPath());
//					files.add(new File(filePath+esv.getPath()));
//					String path = esv.getPath();
//					path = path.substring(path.lastIndexOf("/")+1, path.length());
//					esv.setPath(path);
//				}
//				configContent = JaxbMapper.toXml(esvg, encoding);
//				config = new File(configName);
//				FileUtils.writeStringToFile(config, configContent,encoding, false);
//				files.add(config);
//				break;
                case "multimedia":
                    EleSourceMultimedia eleSourceMultimedia = eleSourceMultimediaService.get(es.getContent());
                    String videoId = eleSourceMultimedia.getVideoId();
                    String imageId = eleSourceMultimedia.getImageId();
                    if(!StringUtils.isEmpty(videoId)){
                        EleSourceVideoGroup esvg = eleSourceVideoGroupService.get(videoId);
                        List<EleSourceVideo> esvList = esvg.getEleSourceVideoList();
                        for(EleSourceVideo esv : esvList){
                            System.out.println(esv.getPath());
                            files.add(new File(filePath + esv.getPath()));
                            String path = esv.getPath();
                            path = path.substring(path.lastIndexOf("/") + 1, path.length());
                            esv.setPath(path);
                        }
                        eleSourceMultimedia.setVideoGroup(esvg);
                    }
                    if(!StringUtils.isEmpty(imageId)){
                        EleSourceImageGroup esig = eleSourceImageGroupService.get(imageId);
                        List<EleSourceImage> esiList = esig.getEleSourceImageList();
                        for(EleSourceImage esi : esiList){
                            files.add(new File(filePath + esi.getPath()));
                            String path = esi.getPath();
                            path = path.substring(path.lastIndexOf("/") + 1, path.length());
                            esi.setPath(path);
                        }
                        eleSourceMultimedia.setImageGroup(esig);
                    }
                    configContent = JaxbMapper.toXml(eleSourceMultimedia, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "sub":
                    EleSourceSubtitleGroup essg = eleSourceSubtitleGroupService.get(es.getContent());
                    if(essg.getBgimage() != null){
                        files.add(new File(filePath + essg.getBgimage()));
                        String image = essg.getBgimage();
                        image = image.substring(image.lastIndexOf("/") + 1, image.length());
                        essg.setBgimage(image);
                    }
                    essg.setBgcolor(essg.getBgcolor().replace("#", ""));
                    essg.setFgcolor(ColorUtils.rgba2rgb(essg.getFgcolor()));
                    configContent = JaxbMapper.toXml(essg, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "title":
                    EleSourceTitle est = eleSourceTitleService.get(es.getContent());
                    est.setBgcolor(est.getBgcolor().replace("#", ""));
                    est.setFgcolor(ColorUtils.rgba2rgb(est.getFgcolor()));
                    configContent = JaxbMapper.toXml(est, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "direction":
                    EleSourceDirectionGroup esdg = eleSourceDirectionGroupService.get(es.getContent());
                    if(esdg.getStop() != null){
                        files.add(new File(filePath + esdg.getStop()));
                        String stop = esdg.getStop();
                        stop = stop.substring(stop.lastIndexOf("/") + 1, stop.length());
                        esdg.setStop(stop);
                    }
                    if(esdg.getUptips() != null){
                        files.add(new File(filePath + esdg.getUptips()));
                        String uptips = esdg.getUptips();
                        uptips = uptips.substring(uptips.lastIndexOf("/") + 1, uptips.length());
                        esdg.setUptips(uptips);
                    }
                    if(esdg.getUpstop() != null){
                        files.add(new File(filePath + esdg.getUpstop()));
                        String upstop = esdg.getUpstop();
                        upstop = upstop.substring(upstop.lastIndexOf("/") + 1, upstop.length());
                        esdg.setUpstop(upstop);
                    }
                    if(esdg.getDeftips() != null){
                        files.add(new File(filePath + esdg.getDeftips()));
                        String deftips = esdg.getDeftips();
                        deftips = deftips.substring(deftips.lastIndexOf("/") + 1, deftips.length());
                        esdg.setDeftips(deftips);
                    }
                    if(esdg.getDownstop() != null){
                        files.add(new File(filePath + esdg.getDownstop()));
                        String downstop = esdg.getDownstop();
                        downstop = downstop.substring(downstop.lastIndexOf("/") + 1, downstop.length());
                        esdg.setDownstop(downstop);
                    }
                    if(esdg.getDowntips() != null){
                        files.add(new File(filePath + esdg.getDowntips()));
                        String downtips = esdg.getDowntips();
                        downtips = downtips.substring(downtips.lastIndexOf("/") + 1, downtips.length());
                        esdg.setDowntips(downtips);
                    }
                    for(EleSourceDirection ed : esdg.getEleSourceDirectionList()){
                        String node = ed.getNode();
                        node = node.substring(node.lastIndexOf("/") + 1, node.length());
                        ed.setNode(node);
                    }
                    esdg.devide();
                    configContent = JaxbMapper.toXml(esdg, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "background":
                    EleSourceBackground esbg = eleSourceBackgroundService.get(es.getContent());
                    if(esbg.getBgGif() != null){
                        files.add(new File(filePath + esbg.getBgGif()));
                        String gif = esbg.getBgGif();
                        gif = gif.substring(gif.lastIndexOf("/") + 1, gif.length());
                        esbg.setBgGif(gif);
                    }
                    if(esbg.getBgImage() != null){
                        files.add(new File(filePath + esbg.getBgImage()));
                        String image = esbg.getBgImage();
                        image = image.substring(image.lastIndexOf("/") + 1, image.length());
                        esbg.setBgImage(image);
                    }
                    esbg.setColor(esbg.getColor().replace("#", ""));
                    configContent = JaxbMapper.toXml(esbg, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "alarm":
                    EleSourceAlarmGroup esag = eleSourceAlarmGroupService.get(es.getContent());
                    List<EleSourceAlarm> eaList = esag.getEleSourceAlarmList();
                    if(esag.getDefaudio() != null){
                        files.add(new File(filePath + esag.getDefaudio()));

                        String def = esag.getDefaudio();
                        def = def.substring(def.lastIndexOf("/") + 1, def.length());
                        esag.setDefaudio(def);
                    }
                    for(EleSourceAlarm ea : eaList){
                        files.add(new File(filePath + ea.getVolume()));
                        files.add(new File(filePath + ea.getImage()));

                        String volume = ea.getVolume();
                        volume = volume.substring(volume.lastIndexOf("/") + 1, volume.length());
                        ea.setVolume(volume);

                        String image = ea.getImage();
                        image = image.substring(image.lastIndexOf("/") + 1, image.length());
                        ea.setImage(image);
                    }
                    configContent = JaxbMapper.toXml(esag, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "date":
                    EleSourceDate esd = eleSourceDateService.get(es.getContent());
                    esd.setFgcolor(ColorUtils.rgba2rgb(esd.getFgcolor()));

                    configContent = JaxbMapper.toXml(esd, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "time":
                    EleSourceTime estime = eleSourceTimeService.get(es.getContent());
                    estime.setFgcolor(ColorUtils.rgba2rgb(estime.getFgcolor()));

                    configContent = JaxbMapper.toXml(estime, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "weather":
                    EleSourceWeather esw = eleSourceWeatherService.get(es.getContent());
                    esw.setFgcolor(ColorUtils.rgba2rgb(esw.getFgcolor()));

                    configContent = JaxbMapper.toXml(esw, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "week":
                    EleSourceWeek esweek = eleSourceWeekService.get(es.getContent());
                    esweek.setFgcolor(ColorUtils.rgba2rgb(esweek.getFgcolor()));

                    configContent = JaxbMapper.toXml(esweek, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "floor":
                    EleSourceFloor esfloor = eleSourceFloorService.get(es.getContent());
                    esfloor.setFloornodes(floorNodeService.getByGroupId(esfloor.getId()));
                    if(esfloor.getVolumeSelect() != null){
                        String volume = esfloor.getVolumeSelect();
                        files.add(new File(filePath + esfloor.getVolumeSelect()));
                        volume = volume.substring(volume.lastIndexOf("/") + 1, volume.length());
                        esfloor.setVolumeSelect(volume);
                    }
                    for(FloorNode f : esfloor.getFloornodes()){
                        if(f.getFloorimg() != null){
                            String image = f.getFloorimg();
                            files.add(new File(filePath + f.getFloorimg()));
                            image = image.substring(image.lastIndexOf("/") + 1, image.length());
                            f.setFloorimg(image);
                        }
                    }
                    for(Floor f : esfloor.getFloors()){
                        if(f.getVolumeCn() != null){
                            String volume = f.getVolumeCn();
                            files.add(new File(filePath + f.getVolumeCn()));
                            volume = volume.substring(volume.lastIndexOf("/") + 1, volume.length());
                            f.setVolumeCn(volume);
                            ;
                        }
                        if(f.getVolumeEn() != null){
                            String volume = f.getVolumeEn();
                            files.add(new File(filePath + f.getVolumeEn()));
                            volume = volume.substring(volume.lastIndexOf("/") + 1, volume.length());
                            f.setVolumeEn(volume);
                        }
                    }
                    configContent = JaxbMapper.toXml(esfloor, encoding).replaceAll("<floorimg>", "").replaceAll("</floorimg>", "");
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                case "floored":
                case "registerfloor":
                    EleSourceFloored esfloored = eleSourceFlooredService.get(es.getContent());
                    configContent = JaxbMapper.toXml(esfloored, encoding);
                    config = new File(configName);
                    FileUtils.writeStringToFile(config, configContent, encoding, false);
                    files.add(config);
                    break;
                default:
                    break;
            }
            fileMap.put(type, files);
            System.out.println(configContent);
        }

        String zipPath = basePath + "/theme/source/" + egId + "/";
        String zipName = egId + ".zip";
        if(eleSourceGroup.getTemplet() != null && !StringUtils.isEmpty(eleSourceGroup.getTemplet().getId())){
            String templateId = eleSourceGroup.getTemplet().getId();

            EleTemplet eleTemplet = eleTempletService.get(templateId);

            Map<String, List<File>> templateConfig = eleTempletService.getTemplateConfigMap(eleTemplet, basePath);
            fileMap.putAll(templateConfig);

        }
        return zipFiles(zipPath, zipName, fileMap);

    }

    public boolean zipFiles(String zipPath, String zipName, Map<String, List<File>> map){

        File tmpZipFile = null;
        ZipOutputStream out = null;
        FileInputStream fis = null;
        // String tmpFileName = "report.zip";
        byte[] buffer = new byte[1024];
        // String strZipPath =
        // COM_REPORT_PATH+"/"+user.getOid()+"/"+report.getOid()+"/"+tmpFileName;

        String strZipPath = zipPath + "/" + zipName;
        try{
            File tmpZip = new File(zipPath);
            if(!tmpZip.exists())
                tmpZip.mkdirs();
            tmpZipFile = new File(strZipPath);
            if(!tmpZipFile.exists())
                tmpZipFile.createNewFile();

            out = new ZipOutputStream(new FileOutputStream(strZipPath));
            Set<String> keys = map.keySet();
            for(String key : keys){
                List<File> files = map.get(key);
                String dir = key + "/";
                if(key.equals("theme")){
                    dir = "/";
                }
                //增加外部文件夹
                out.putNextEntry(new ZipEntry(dir));
                System.out.println(key);
                System.out.println(files.size());
                for(int i = 0; i < files.size(); i++){
                    File f = files.get(i);
                    if(f.isDirectory()){
                        continue;
                    }
                    fis = new FileInputStream(f);
                    out.putNextEntry(new ZipEntry(dir + files.get(i).getName()));
                    // 设置压缩文件内的字符编码，不然会变成乱码
                    out.setEncoding("UTF-8");
                    int len;
                    // 读入需要下载的文件的内容，打包到zip文件
                    while((len = fis.read(buffer)) > 0){
                        out.write(buffer, 0, len);
                    }
                    out.closeEntry();
                    fis.close();
                }
                out.closeEntry();
            }
            out.close();
            return true;
        }
        catch(Exception e){
            if(fis != null) {
                try{
                    fis.close();
                } catch(Exception ex) {

                }
            }
            if(out != null) {
                try{
                    out.closeEntry();
                } catch(Exception ex) {

                }
                try{
                    out.close();
                } catch(Exception ex) {

                }
            }
            if(tmpZipFile!= null && tmpZipFile.exists())
                tmpZipFile.delete();
            logger.error("生成zip文件失败!", e);
            return false;
        }
    }

    @RequiresPermissions("source:eleSourceGroup:edit")
    @RequestMapping(value = "download")
    public String download(EleSourceGroup eleSourceGroup, Model model, HttpServletRequest request,
                         HttpServletResponse response, RedirectAttributes redirectAttributes){
        if(!beanValidator(model, eleSourceGroup)){
            return "redirect:"+Global.getAdminPath()+"/source/eleSourceGroup/?repage";
        }
        System.out.println(eleSourceGroup);
        String basePath = Global.getUserfilesBaseDir();
        System.out.println(basePath);
        try{
            createPackageForSourceGroup(eleSourceGroup, basePath);
        }
        catch(IOException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(!eleSourceGroupService.resourceFileExistById(eleSourceGroup.getId())) {
            String locale = I18nUtils.getLocaleStr();
            String msg = "该资源对应文件不存在，请重新编辑保存后再尝试";
            if(Global.US.equals(locale)){
                msg = "The resource corresponding file does not exist, please re-edit it and try again";
            }
            addMessage(redirectAttributes, msg);
            return "redirect:"+Global.getAdminPath()+"/source/eleSourceGroup/?repage";
        }
        String zipPath = basePath + "/theme/source/" + eleSourceGroup.getId() + "/";
        String zipName = eleSourceGroup.getId() + ".zip";
        downloadFile(zipPath, zipName, response);
        return "";
    }

    @RequiresPermissions("source:eleSourceGroup:publish")
    @RequestMapping(value = "applypublish")
    public String applypublish(EleSourceGroup eleSourceGroup,  RedirectAttributes redirectAttributes, EleEquipment eleEquipment, Model model){
        // Edited by jyz (2018.5)
        String basePath = Global.getUserfilesBaseDir();
        System.out.println(basePath);
        try{
            createPackageForSourceGroup(eleSourceGroup, basePath);
        }
        catch(IOException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(!eleSourceGroupService.resourceFileExistById(eleSourceGroup.getId())) {
            String locale = I18nUtils.getLocaleStr();
            String msg = "该资源对应文件不存在，请重新编辑保存后再尝试";
            if(Global.US.equals(locale)){
                msg = "The resource corresponding file does not exist, please re-edit it and try again";
            }
            addMessage(redirectAttributes, msg);
            return "redirect:"+Global.getAdminPath()+"/source/eleSourceGroup/?repage";
        }

        List<Office> listTree = new ArrayList<>();

        User current = UserUtils.getUser();

        List<User> resultList = getBranchForUser(current);
        Set<String> ids = new HashSet<String>();
        for(User temuser : resultList){
            String officeId = temuser.getOffice().getId();
            String companyId = temuser.getCompany().getId();
            ids.add(officeId);
            ids.add(companyId);
        }
        List<Office> listOffice = officeService.findList(true);

        Set<String> officeIds = new HashSet<>();
        Set<String> eqIds = new HashSet<>();
        for(User tmp : resultList){
            EleEquipment eleEquipmentTmp = new EleEquipment();
            eleEquipmentTmp.setCompany(tmp.getCompany());
            eleEquipmentTmp.setOffice(tmp.getOffice());

            List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipmentTmp);
            for(EleEquipment equipment : listEquipment){
                officeIds.add(equipment.getCompany().getId());
                officeIds.add(equipment.getOffice().getId());
                if(eqIds.contains(equipment.getId())){
                    continue;
                }
                eqIds.add(equipment.getId());
                Office Office = new Office();
                Office.setId(equipment.getId());
                Office.setParent(new Office(equipment.getOffice().getId()));
                Office.setAddress(equipment.getCode());
                Office.setEmail(equipment.getType().getName());
                Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
                Office.setRemarks(equipment.getRemarks());
                if("1".equals(equipment.getState())){
                    Office.setGrade("在线");
                }
                else{
                    Office.setGrade("离线");
                }
                Office.setPhone("");
				Office.setZipCode(equipment.getName());

                listTree.add(Office);
            }
        }
        Set<String> resultSet = new HashSet<String>();
        for(String oid : officeIds){
            resultSet.add(oid);
            Office tmp = officeService.get(oid);
            for(int i = 0; i < listOffice.size(); i++){
                Office item = listOffice.get(i);
                if(item.getId().equals(tmp.getParentId())){
                    System.out.println(item);
                    tmp = item;
                    i = -1;
                    resultSet.add(item.getId());
                }
            }
        }
        for(String oid : resultSet){
            Office item = officeService.get(oid);
            item.setAddress(null);
            item.setEmail(null);
            item.setFax(null);
            item.setRemarks(null);
            item.setGrade(null);
            item.setPhone("display:none;");
			item.setZipCode("");

            listTree.add(item);
        }
        model.addAttribute("list", listTree);
        model.addAttribute("user", current);
        model.addAttribute("eleEquipment", eleEquipment);
        model.addAttribute("eleSourceGroup", eleSourceGroup);
        model.addAttribute("resourcetype", "other");

        return "modules/source/eleSourceGroupPublish";
    }

    @RequestMapping(value = "publish")
    @ResponseBody
    public Result publish(String equipmentLists, String egId, HttpServletRequest request){
        User thisuser = UserUtils.getUser();

        String[] ems = equipmentLists.split(",");
        boolean noNeedCheck = false;
        //UserUtils.getSubject().isPermitted("source:eleSourceGroup:check")
        //        || SwitchUtils.isClose("equipment:eleEquipment:check");
        System.out.println(egId);

        EleSourceGroup group = eleSourceGroupService.getGroupById(egId);
        System.out.println(group);

        // 设置 申请 批次
        String publishBatch = IdGen.uuid();
        List<EleSourceGroupPublish> publishList = new ArrayList<>();
        for(String emId : ems){
            if(StringUtils.isNotBlank(emId)){
                EleSourceGroupPublish esgp = new EleSourceGroupPublish();
                esgp.setPublishBatch(publishBatch);
                esgp.setEquipmentId(emId);
                esgp.setGroupId(egId);
                //if(noNeedCheck || group.getVisible().equals("0")){
                    esgp.setCheckBy(thisuser);
                    esgp.setCheckDate(new Date(System.currentTimeMillis()));
                    esgp.setDelFlag(EleSourceGroupPublish.DEL_FLAG_NORMAL);
                //}
                //else{
                //    esgp.setCheckBy(UserUtils.getCheckUser(""));
                //    esgp.setDelFlag(EleSourceGroupPublish.DEL_FLAG_AUDIT);
                //}
                publishList.add(esgp);
            }
        }
        eleSourceGroupPublishService.batchInsertSource(publishList);

        //return new Result(Result.SUCCESS, noNeedCheck ? "发布成功!" : "提交发布申请,等待管理员审核!", null);
        String locale = I18nUtils.getLocaleStr();
        String msg = "发布成功";
        if(Global.US.equals(locale)){
            msg = "Publish Successful";
        }
        return new Result(Result.SUCCESS, msg, null);

    }


    public void downloadFile(String filePath, String fileName, HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        // response.setContentType("application/octet-stream");

        try{
            File file = new File(filePath, fileName);
            // 以流的形式下载文件。
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            toClient.write(buffer);
            toClient.flush();
            toClient.close();

        }
        catch(IOException ex){
            ex.printStackTrace();
        }
    }

    @RequiresPermissions("source:eleSourceGroup:edit")
    @RequestMapping(value = "delete")
    public String delete(EleSourceGroup eleSourceGroup, RedirectAttributes redirectAttributes){
        eleSourceGroupService.delete(eleSourceGroup);
        String locale = I18nUtils.getLocaleStr();
        String msg = "删除节目包成功";
        if(Global.US.equals(locale)){
            msg = "Programpackage deleted";
        }
        addMessage(redirectAttributes, msg);
        return "redirect:" + Global.getAdminPath() + "/source/eleSourceGroup/?repage";
    }

    @RequiresPermissions("source:eleSourceGroup:edit")
    @RequestMapping(value = "deleteSource")
    public String deleteSource(RedirectAttributes redirectAttributes, HttpServletRequest request){
        String id = request.getParameter("sourceid");
        System.out.println(id);
        EleSource es = eleSourceGroupService.getSourceById(id);
        System.out.println(es);
        eleSourceGroupService.deleteSource(es);
        String locale = I18nUtils.getLocaleStr();
        String msg = "删除节目成功";
        if(Global.US.equals(locale)){
            msg = "Programpackage deleted";
        }
        addMessage(redirectAttributes, msg);
        return "redirect:" + Global.getAdminPath() + "/source/eleSourceGroup/?repage";
    }

    /**
     * 申请记录
     *
     * @param eleSourceGroupPublish
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("source:eleSourceGroup:edit")
    @RequestMapping("applylist")
    public String applylist(EleSourceGroup eleSourceGroup, String isFirst, HttpServletRequest request, HttpServletResponse response, Model model){
    	User thisUser = UserUtils.getUser();
    	//eleSourceGroup.setCreateBy(thisUser);
		if (StringUtils.isEmpty(isFirst)) {
			eleSourceGroup.setDelFlag(User.DEL_FLAG_AUDIT);
		}
		List<User> list = new ArrayList<>();
		list.add(thisUser);
    	eleSourceGroup.setUsers(list);
    	eleSourceGroup.setVisible("0");
        Page<EleSourceGroup> page = eleSourceGroupService.findPage(new Page<EleSourceGroup>(request, response),
                eleSourceGroup);
        Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
        model.addAttribute("page", page);
		model.addAttribute("isFirst", "no");

        return "modules/source/eleSourceGroupApplyList";
    }

    @RequiresPermissions("source:eleSourceGroup:check")
    @RequestMapping("mychecklist")
    public String mychecklist(EleSourceGroupPublish eleSourceGroupPublish, String isFirst, HttpServletRequest request, HttpServletResponse response,
                              Model model){

        User thisuser = UserUtils.getUser();
        if(StringUtils.isEmpty(isFirst)){
            eleSourceGroupPublish.setDelFlag(User.DEL_FLAG_AUDIT);
        }
        List<User> branches = this.getSubListForUserForCheck(thisuser);
        Page<EleSourceGroupPublish> page = new Page<>();
        if(!branches.isEmpty()){
            page = eleSourceGroupPublishService.findPageForCheck(new Page<EleSourceGroupPublish>(request, response),
                    branches, eleSourceGroupPublish.getDelFlag());
        }
        Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
        model.addAttribute("page", page);
        model.addAttribute("flag", request.getParameter("flag"));
        model.addAttribute("isFirst", "no");

        return "modules/source/eleSourceGroupCheckList";
    }

    @RequiresPermissions("source:eleSourceGroup:edit")
    @RequestMapping("resubmit")
    @ResponseBody
    public Result resubmitSourceGroup(String groupList, HttpServletRequest request, HttpServletResponse response,
                                      Model model){
        String groups = groupList.substring(0, groupList.length() - 1);

        System.out.println(groups);

        String status = EleTempletPublish.DEL_FLAG_AUDIT;
        String msg = "已重新提交审核";
        User thisuser = UserUtils.getUser();
        eleSourceGroupPublishService.bathcUpdateGroupStatus(groups, status, thisuser.getId());

        return new Result(Result.SUCCESS, msg, null);
    }

    @RequiresPermissions("source:eleSourceGroup:check")
    @RequestMapping("checkList")
    @ResponseBody
    public Result checkList(String groupList, String flag, String type){
        String groups = groupList.substring(0, groupList.length() - 1);

        System.out.println(groups);

        String status;
        String msg;
        if("delete".equals(flag)){
            status = EleSourceGroup.DEL_FLAG_DELETE;
            String locale = I18nUtils.getLocaleStr();
            msg = "删除成功";
            if(Global.US.equals(locale)){
                msg = "Deleted";
            }
            if("approval".equals(type)){
                eleSourceGroupPublishService.dealApprovalGroupStatus(groups, status);
            }
            else{
                eleSourceGroupPublishService.dealApplyGroupStatus(groups, status);
            }
            return new Result(Result.SUCCESS, msg, null);
        }

        if("reject".equals(flag)){
            status = EleSourceGroup.DEL_FLAG_AUDIT_NO;
            String locale = I18nUtils.getLocaleStr();
            msg = "未通过审核";
            if(Global.US.equals(locale)){
                msg = "Not passed";
            }
        }
        else{
            status = EleSourceGroup.DEL_FLAG_NORMAL;
            String locale = I18nUtils.getLocaleStr();
            msg = "审核通过";
            if(Global.US.equals(locale)){
                msg = "passed";
            }
        }
        User thisuser = UserUtils.getUser();
        eleSourceGroupPublishService.bathcUpdateGroupStatus(groups, status, thisuser.getId());

        return new Result(Result.SUCCESS, msg, null);
    }

    @RequestMapping(value = "treeData")
    @ResponseBody
    public List<Map<String, Object>> treeData(HttpServletRequest request){
        String sourceType = request.getParameter("sourceType");
        List<Map<String, Object>> mapList = Lists.newArrayList();

        User user = UserUtils.getUser();
        List<User> list = null;
        if(user.isAdmin()) {
            list = systemService.findAllUsers(user);
        }else {
            list = systemService.findAllUsersInCompany(user);
            list.add(UserUtils.getAdminUser());
        }
        switch(sourceType){
            case "video":
                EleSourceVideoGroup eleSourceVideoGroup = new EleSourceVideoGroup();
                List<EleSourceVideoGroup> esvList = eleSourceVideoGroupService.findList(eleSourceVideoGroup);
                for(EleSourceVideoGroup e : esvList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "image":
                EleSourceImageGroup eleSourceImageGroup = new EleSourceImageGroup();
                List<EleSourceImageGroup> esigList = eleSourceImageGroupService.findList(eleSourceImageGroup);
                for(EleSourceImageGroup e : esigList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "multimedia":
                EleSourceMultimedia eleSourceMultimedia = new EleSourceMultimedia();
                eleSourceMultimedia.setUsers(list);
                List<EleSourceMultimedia> esmtList = eleSourceMultimediaService.findList(eleSourceMultimedia);
                if(CollectionUtils.isNotEmpty(esmtList)){
                    for(EleSourceMultimedia e : esmtList){
                        Map<String, Object> map = Maps.newHashMap();
                        map.put("id", e.getId());
                        map.put("pId", e.getId());
                        map.put("pIds", e.getId());
                        map.put("name", e.getName());
                        map.put("sourceType", sourceType);

                        map.put("view", preview(e));

                        mapList.add(map);
                    }
                }
                break;
            case "sub":
                EleSourceSubtitleGroup essg = new EleSourceSubtitleGroup();
                essg.setUsers(list);
                List<EleSourceSubtitleGroup> essgList = eleSourceSubtitleGroupService.findList(essg);
                for(EleSourceSubtitleGroup e : essgList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "title":
                EleSourceTitle est = new EleSourceTitle();
                est.setUsers(list);
                List<EleSourceTitle> estList = eleSourceTitleService.findList(est);
                for(EleSourceTitle e : estList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "time":
                EleSourceTime estime = new EleSourceTime();
                estime.setUsers(list);
                List<EleSourceTime> estimeList = eleSourceTimeService.findList(estime);
                for(EleSourceTime e : estimeList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "date":
                EleSourceDate esdate = new EleSourceDate();
                esdate.setUsers(list);
                List<EleSourceDate> esdateList = eleSourceDateService.findList(esdate);
                for(EleSourceDate e : esdateList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "direction":
                EleSourceDirectionGroup esdg = new EleSourceDirectionGroup();
                esdg.setUsers(list);
                List<EleSourceDirectionGroup> esdgList = eleSourceDirectionGroupService.findList(esdg);
                for(EleSourceDirectionGroup e : esdgList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "alarm":
                EleSourceAlarmGroup esag = new EleSourceAlarmGroup();
                esag.setUsers(list);
                List<EleSourceAlarmGroup> esagList = eleSourceAlarmGroupService.findList(esag);
                for(EleSourceAlarmGroup e : esagList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "background":
                EleSourceBackground esbg = new EleSourceBackground();
                esbg.setUsers(list);
                List<EleSourceBackground> esbgList = eleSourceBackgroundService.findList(esbg);
                for(EleSourceBackground e : esbgList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "floor":
                EleSourceFloor esfloor = new EleSourceFloor();
                esfloor.setUsers(list);
                List<EleSourceFloor> esfloorList = eleSourceFloorService.findList(esfloor);
                for(EleSourceFloor e : esfloorList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "floored":
            case "registerfloor":
                EleSourceFloored esfloored = new EleSourceFloored();
                esfloored.setUsers(list);
                List<EleSourceFloored> esflooredList = eleSourceFlooredService.findList(esfloored);
                for(EleSourceFloored e : esflooredList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "weather":
                EleSourceWeather esweather = new EleSourceWeather();
                esweather.setUsers(list);
                List<EleSourceWeather> esweatherList = eleSourceWeatherService.findList(esweather);
                for(EleSourceWeather e : esweatherList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "logo":
                EleSourceLogo logo = new EleSourceLogo();
                logo.setUsers(list);
                List<EleSourceLogo> logoList = eleSourceLogoService.findList(logo);
                for(EleSourceLogo e : logoList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "week":
                EleSourceWeek esweek = new EleSourceWeek();
                esweek.setUsers(list);
                List<EleSourceWeek> esweekList = eleSourceWeekService.findList(esweek);
                for(EleSourceWeek e : esweekList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    map.put("sourceType", sourceType);

                    map.put("view", preview(e));

                    mapList.add(map);
                }
                break;
            case "apk":
                EleSourceApp sourceApp = new EleSourceApp();
                List<EleSourceApp> appList = eleSourceAppService.findList(sourceApp);
                for(EleSourceApp e : appList){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getId());
                    map.put("pIds", e.getId());
                    map.put("name", e.getName());
                    mapList.add(map);
                }
                break;

            default:
                break;
        }

        return mapList;

    }

    public Map<String, Object> preview(Object object){
        //====================================字典map=======================================
        Map<String,String> alignDictMap = new HashMap<>();
        List<Dict> dictList = DictUtils.getDictList("textalign");
        for(Dict dict:dictList){
            alignDictMap.put(dict.getValue(), dict.getRemarks());
        }

        Map<String, Object> source = new HashMap<>();

        if(object instanceof EleSourceDate){
            EleSourceDate date = (EleSourceDate)object;
            source.put("content", DateUtils.getDate(date.getFormat()));
            source.put("color", date.getFgcolor());
            source.put("bgcolor", date.getBgcolor());
            source.put("size", date.getSize());
            source.put("align", alignDictMap.get(date.getAlign()));
        }
        else if(object instanceof EleSourceTime){
            EleSourceTime time = (EleSourceTime)object;
            source.put("content", DateUtils.getTimeByField(time.getFormat()));
            source.put("color", time.getFgcolor());
            source.put("bgcolor", time.getBgcolor());
            source.put("size", time.getSize());
            source.put("align", alignDictMap.get(time.getAlign()));
        }
        else if(object instanceof EleSourceWeek){
            EleSourceWeek week = (EleSourceWeek)object;
            source.put("content", DateUtils.getWeekStr());
            source.put("color", week.getFgcolor());
            source.put("bgcolor", week.getBgcolor());
            source.put("size", week.getSize());
            source.put("align", alignDictMap.get(week.getAlign()));
        }
        else if(object instanceof EleSourceTitle){
            EleSourceTitle title = (EleSourceTitle)object;
            source.put("content", title.getContent());
            source.put("color", title.getFgcolor());
            source.put("bgcolor", title.getBgcolor());
            source.put("size", title.getSize());
            source.put("align", alignDictMap.get(title.getAlign()));
        }
        else if(object instanceof EleSourceSubtitleGroup){
            source.put("content", "这个位置将展示字幕信息!");
            source.put("color", "#000000");
            source.put("bgcolor", "#FFFFFF");
            source.put("size", "14");

            EleSourceSubtitleGroup item = (EleSourceSubtitleGroup)object;
            List<EleSourceSubtitle> subtitles = eleSourceSubtitleGroupService.getSubtitlesByGroupId(item.getId());
            if(CollectionUtils.isNotEmpty(subtitles)){
                EleSourceSubtitle subtitle = subtitles.get(0);
                source.put("content", subtitle.getText());
                source.put("color", item.getFgcolor());
                source.put("bgcolor", item.getBgcolor());
                source.put("size", item.getFontsize());

                source.put("align", "center");

                source.put("alpha", item.getAlpha());
            }
        }
        else if(object instanceof EleSourceWeather){
            EleSourceWeather weather = (EleSourceWeather)object;
            String locale = I18nUtils.getLocaleStr();
            if(Global.US.equals(locale)){
                source.put("content", "Sunny");
            } else {
                source.put("content", "晴天");
            }
            source.put("color", weather.getFgcolor());
            source.put("bgcolor", weather.getBgcolor());
            source.put("size", weather.getSize());
            source.put("align", alignDictMap.get(weather.getAlign()));
        }
        else if(object instanceof EleSourceLogo){
            EleSourceLogo logo = (EleSourceLogo)object;
            source.put("imgpath", logo.getPath());
        }
        else if(object instanceof EleSourceFloor){
            source.put("type", "font");
            source.put("content", "FF");

            EleSourceFloor floor = (EleSourceFloor)object;
            if(null != floor){
                source.put("align", alignDictMap.get(String.valueOf(floor.getAlignment())));

                String groupId = floor.getId();

                List<FloorNode> floorNodes = floorNodeService.getByGroupId(groupId);
                if(CollectionUtils.isNotEmpty(floorNodes)){
                    FloorNode floorNode = floorNodes.get(0);
                    source.put("type", "image");
                    source.put("imgpath", floorNode.getFloorimg());
                }
            }
        }
        else if(object instanceof EleSourceFloored){
            EleSourceFloored floored = (EleSourceFloored)object;
            source.put("column", floored.getColumn());
            source.put("width", floored.getColumnWidth());
            source.put("color", floored.getFgcolor());
            source.put("bgcolor", floored.getBgcolor());
            source.put("size", floored.getSize());
            source.put("align", alignDictMap.get(floored.getAlign()));
            source.put("w_space", floored.getHorizontalSpacing());
            source.put("lineheight", floored.getVerticalSpacing());
        }
        else if(object instanceof EleSourceDirectionGroup){
            EleSourceDirectionGroup directionGroup = (EleSourceDirectionGroup)object;
            String path = directionGroup.getUpstop();
            if(StringUtils.isNotEmpty(path)){
                String directionimg = path.replace("|", "");
                source.put("imgpath", directionimg);
            }
        }
        else if(object instanceof EleSourceAlarmGroup){
            source.put("content", "警告");
            source.put("type", "font");

            EleSourceAlarmGroup group = (EleSourceAlarmGroup)object;
            List<EleSourceAlarm> alarms = eleSourceAlarmGroupService.findAlarmsByGroupId(group.getId());

            if(CollectionUtils.isNotEmpty(alarms)){
                EleSourceAlarm alarm = alarms.get(0);
                source.put("type", "image");
                source.put("imgpath", alarm.getImage());
            }
        } else if (object instanceof EleSourceMultimedia) {
            source.put("type", "default");

            EleSourceMultimedia multimedia = (EleSourceMultimedia)object;
            if("image".equals(multimedia.getType())){
                String groupId = multimedia.getImageId();
                List<EleSourceImage> images = imageService.getByGroupId(groupId);
                source.put("type", "image");
                if(CollectionUtils.isNotEmpty(images)){
                    source.put("imgpath", images.get(0).getPath());
                }
            }
            else if("video".equals(multimedia.getType())){
                String groupId = multimedia.getVideoId();
                List<EleSourceVideo> videos = videoService.getByGroupId(groupId);
                source.put("type", "video");
                if(CollectionUtils.isNotEmpty(videos)){
                    source.put("imgpath", videos.get(0).getPath());
                }
            }
        }
        return source;
    }


    public List<User> getSubListForUserForCheck(User current){
        User user = new User();
        user.setDelFlag(null);
        List<User> list = systemService.findList(user);
        Role role = current.getRole();
        List<User> resultList = new ArrayList<>();
        if(current.getUserType().equals("1")){
            for(User usr : list){
                resultList.add(usr);
            }
        }
        else if(current.getUserType().equals("4")){
            //resultList.add(current);
        }
        else if(current.getUserType().equals("3")){
            for(User usr : list){
                if(usr.getUserType().equals("4")
                        && usr.getCompany().getId().equals(current.getCompany().getId()) && usr.getOffice().getId().equals(current.getOffice().getId())){
                    resultList.add(usr);
                }
            }
            //resultList.add(current);
        }
        else{
            Set<String> offices = new HashSet<String>();
            for(User usr : list){
                if(usr.getUserType().equals("3")
                        && usr.getCompany().getId().equals(current.getOffice().getId())){
                    resultList.add(usr);
                    offices.add(usr.getOffice().getId());
                }
            }
            offices.add(current.getOffice().getId());
            for(User usr : list){
                if(usr.getUserType().equals("4") && offices.contains(usr.getCompany().getId())){
                    resultList.add(usr);
                }
            }
            //resultList.add(current);
        }
        for(User temuser : resultList){
            temuser.setRemarks(User.DEL_FLAG_NORMAL.equals(temuser.getDelFlag()) ? "正常" : "审核中");
        }
        return resultList;
    }

    @RequiresPermissions("source:eleSourceGroup:edit")
    @RequestMapping("approvelist")
    public String reviewlist(EleSourceGroup eleSourceGroup, String isFirst, HttpServletRequest request, HttpServletResponse response, Model model){
        User thisuser = UserUtils.getUser();

        if(StringUtils.isEmpty(isFirst)){
            eleSourceGroup.setDelFlag(User.DEL_FLAG_AUDIT);
        }
        List<User> branches = this.getSubListForUserForCheck(thisuser);
        Page<EleSourceGroup> page = new Page<>();
        if(!branches.isEmpty()){
            page = eleSourceGroupService.findPageForCheckForProgram(eleSourceGroup, new Page<EleSourceGroup>(request, response),
                    branches, eleSourceGroup.getDelFlag());
        }
        Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
        model.addAttribute("page", page);
        model.addAttribute("flag", request.getParameter("flag"));
        model.addAttribute("isFirst", "no");

        return "modules/source/eleSourceGroupApproveList";

    }

    @RequiresPermissions("source:eleSourceGroup:check")
    @RequestMapping("approve")
    @ResponseBody
    public Result approve(String groupList, String flag, String type, String comment){
        String groups = groupList.substring(0, groupList.length() - 1);

        System.out.println(groups);

        String status;
        String msg;
        if("delete".equals(flag)){
            status = EleSourceGroup.DEL_FLAG_DELETE;
            String locale = I18nUtils.getLocaleStr();
            msg = "删除成功";
            if(Global.US.equals(locale)){
                msg = "Deleted";
            }
        }
        else if("reject".equals(flag)){
            status = EleSourceGroup.DEL_FLAG_AUDIT_NO;
            String locale = I18nUtils.getLocaleStr();
            msg = "未通过审核";
            if(Global.US.equals(locale)){
                msg = "Not passed";
            }
        }
        else{
            status = EleSourceGroup.DEL_FLAG_NORMAL;
            String locale = I18nUtils.getLocaleStr();
            msg = "审核通过";
            if(Global.US.equals(locale)){
                msg = "passed";
            }
        }
        User thisuser = UserUtils.getUser();
        eleSourceGroupService.bathcUpdateGroupStatus(groups, status, thisuser.getId(), comment);

        return new Result(Result.SUCCESS, msg, null);
    }

}